<template>
  <el-container>
    <el-header>
      <h2>{{ questionnaire.title }}</h2>
      <p>{{ questionnaire.description }}</p>
    </el-header>
    <el-main>
      <el-row justify="center">
        <el-col :span="9" style="min-width: 450px;">
          <div class="selectsty">
            <div class="elselect company-selection">
              <span>单位：</span>
              <el-select filterable clearable v-model="parames.selectCompany" placeholder="请选择企业" size="large"  @change="handleSelectComChange">
                <el-option v-for="item in selectCompanyOption" :key="item.id"  :value="item.name" />
              </el-select>
            </div>
            <div class="elselect system-selection">
              <span>系统：</span>
              <el-select filterable clearable v-model="parames.selectSystem" multiple placeholder="请选择系统" size="large" @change="handleSelectSystemChange" >
                <el-option v-for="item in selectSystemOptions" :key="item.id" :value="item.systemName" :label="item.systemName"  />
              </el-select>
            </div>
          </div>
          
          <CheckBox 
            ref="CheckBoxRef"
            v-if="parames.selectSystem.length > 1"
            :name="cname"
            :companyName="companyName"
            :companyId="companyId" 
            :textareaValue="parames.textareaValue" 
            @clear="clearValue"
            />
          <Radio 
            ref="RadioRef"
            v-if="parames.selectSystem.length === 1 || parames.selectSystem.length === 0"
            :name="cname"
            :companyName="companyName"
            :companyId="companyId" 
            :textareaValue="parames.textareaValue" 
            @clear="clearValue"
            />
            
          <p>{{ questionnaire.endSay }}</p>
          <el-input v-model="parames.textareaValue" style="width: 100%" :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea" placeholder="" />
          <p>{{ questionnaire.againEndSay }}</p>
        </el-col>
      </el-row>
    </el-main>

    <el-footer class="fixed-footer">
      <el-button type="primary" @click="submitAnswers">提交问卷</el-button>
    </el-footer>
  </el-container>
</template>


<script>
import { computed, ref, reactive, onMounted, getCurrentInstance   } from 'vue';
import { ElMessage,ElMessageBox } from 'element-plus';
import questionnaire from '@/assets/js/surveyConfig';
import api from '@/assets/js/api.js'; // 导入公用接口文件
import Radio from '@/components/Radio.vue';
import CheckBox from '@/components/CheckBox.vue';

export default {
  name: 'Questionnaire',
  components:{Radio, CheckBox},
  setup() {
    // const companyName = computed(() => ["营销智慧引擎", "用电信息采集系统"]);
    const companyName = computed(() => parames.selectSystem);
    const companyId = computed(() => parames1.value.systemId);
    const cname = computed(() => parames1.value.cname);
    const textareaValue = computed(() => parames1.value.textareaValue);
    // 获取组件实例
    const { proxy } = getCurrentInstance();

    const parames = reactive({
      selectCompany: '',
      // selectSystem: ["营销智慧引擎", "用电信息采集系统"],
      selectSystem: [],
      textareaValue: '',
    });
    
    // 定义数据
    const parames1 = ref({
      cname: "",
      textareaValue: "",
      systemName: [],
      systemId: [],
    });
    console.log(parames.selectSystem);

    // 新增变量 isSystemSelected 用于检查是否已选择系统
    const isSystemSelected = ref(false);
    const answers = reactive({});
    const selectedSystemMap = reactive([]); // 追踪每个题目选项的系统选择
    const questionSystemSelections = reactive({}); // 追踪每个题目中已选择的系统

    // 初始化 answers 回显
    const selectSystemDatas = ref([]);  
    const dataName = {
      "unitName": "国网四川省电力公司天府新区供电公司"
      };
    const fetchDataAnsers = async () => {
      try {
        let data = await api.post('/system/questionnaire/get',dataName); 
        console.log('获取数据',data);
        parames.selectCompany = data.unitName;
        parames.selectSystem = data.systemNames || [];
        selectSystemDatas.value = data.value; // 赋值
        parames1.value.systemName = data.systemNames || [];
        initializeSelectedSystems(data.value);
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    };
    
    // 初始化已选系统到 selectedSystemMap 回显
    const initializeSelectedSystems = (selectSystemDatas) => {
      console.log(selectSystemDatas);

      if (!selectSystemDatas || Object.keys(selectSystemDatas).length === 0) return;
        
      Object.entries(selectSystemDatas).forEach(([questionId, options]) => {
        answers[questionId] = Object.keys(options);
        
        Object.entries(options).forEach(([option, systems]) => {
          const key = `${questionId}-${option}`;
          selectedSystemMap[key] = systems || [];
        });
        // });
      // Object.entries(selectSystemDatas).forEach(([questionId, options]) => {
      //   // 初始化问题的选项选择
      //   answers[questionId] = Object.keys(options);

      //   // 初始化每个选项的系统选择
      //   Object.entries(options).forEach(([option, systems]) => {
      //     const key = `${questionId}-${option}`;
      //     selectedSystemMap[key] = systems;
      //   });

        console.log(answers[questionId]);
        
        // 检查每个勾选的选项是否有系统选中，如果没有则取消勾选
        // answers[questionId].forEach((option) => {
        //   const key = `${questionId}-${option}`;

        //   if (!selectedSystemMap[key] || selectedSystemMap[key].length === 0) {
        //     const index = answers[questionId].indexOf(option);
        //     if (index > -1) answers[questionId].splice(index, 1); // 取消该选项的勾选状态
        //   }
        // });
      });
    };
    
    // 获取系统
    const selectSystemOptions = ref([]);  
    const dataSystem = ref(null);
    const fetchDataSystem = async () => {
      try {
        dataSystem.value = await api.get('/system/system/list'); 
        selectSystemOptions.value = dataSystem.value.list; // 赋值
        
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    };
    // 获取企业
    const selectCompanyOption = ref([]); // 确保使用 ref
    const dataCompany = ref(null);

    const fetchDataCompany = async () => {
      try {
        dataCompany.value = await api.get('/system/unit/list');
        selectCompanyOption.value = dataCompany.value.list; // 赋值
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    };

    // 获取企业
    const handleSelectComChange = (value) =>{
      parames1.value.cname = value;  
      parames.selectCompany = value;  
    }

    const handleSelectSystemChange = (value) => {
      parames.selectSystem = value;  
      parames1.value.systemName = value;  
      console.log("parames.selectSystem:", parames.selectSystem);
      isSystemSelected.value = value.length > 0;  
 
      parames1.value.systemId = parames1.value.systemName.map((id) => {
        const matchedItem = selectSystemOptions.value.find((item) => item.systemName === id);
        return matchedItem ? matchedItem.id : null;
      });

      console.log("Selected Names:", parames1.value.systemId);
    };
    // const handleSelectSystemChange = (value) => {
    //   parames1.value.systemName = value;
    //   console.log("parames.selectSystem (IDs):", parames1.value.systemName);
    //   console.log("parames.selectSystem:", parames.selectSystem);
    //   isSystemSelected.value = value.length > 0; // 检查是否已选择至少一个系统

    //   // 根据 ID 查找对应的名称
    //   parames1.value.systemId = parames1.value.systemName.map((id) => {
    //     const matchedItem = selectSystemOptions.value.find((item) => item.systemName === id);
    //     return matchedItem ? matchedItem.id : null;
    //   });

    //   console.log("Selected Names:", parames1.value.systemId);
    // };


    // 提交数据
    const submitAnswers = async () => {
      if (!parames.selectCompany) {
        scrollToElement('.company-selection'); // 滚动到公司选择位置
        ElMessage.warning("请选择企业！");
        return;
      }
      if (!parames1.value.systemName || parames1.value.systemName.length === 0) {
        scrollToElement('.system-selection'); // 滚动到系统选择位置
        ElMessage.warning("请选择系统，选择系统后才能作答！");
        return;
      }
      console.log(selectedSystemMap);
      if (parames.selectSystem.length > 1) {
        const checkBoxSubmit = await proxy.$refs.CheckBoxRef?.submitAnswers();
        // console.log("CheckBox submitAnswers result:", checkBoxSubmit);
      }
      else if (parames.selectSystem.length === 1 || parames.selectSystem.length === 0){
        const radioSubmit = await proxy.$refs.RadioRef?.submitAnswers();
        // console.log("Radio submitAnswers result:", radioSubmit);
      }
    };
    // 重置数据
    const resetForm = () => {
      parames.selectCompany = '';
      parames.selectSystem = [];
      parames.textareaValue = '';
      parames1.value.selectSystem = [];
      parames1.value.selectedNames = [];
      Object.keys(answers).forEach(key => delete answers[key]);
      Object.keys(selectedSystemMap).forEach(key => delete selectedSystemMap[key]);
      Object.keys(questionSystemSelections).forEach(key => delete questionSystemSelections[key]);
    };
    // 滚动到指定元素
    const scrollToElement = (selector) => {
      const element = document.querySelector(selector);
      if (element) {
        element.scrollIntoView({ behavior: 'smooth' });
      }
    };
    const clearValue = () => {
      parames.selectCompany = '';
      parames.selectSystem = [];
      parames.textareaValue = '';
      parames1.value.selectSystem = [];
      parames1.value.selectedNames = [];
      Object.keys(answers).forEach(key => delete answers[key]);
      Object.keys(selectedSystemMap).forEach(key => delete selectedSystemMap[key]);
      Object.keys(questionSystemSelections).forEach(key => delete questionSystemSelections[key]);
    };
    // 组件挂载后获取数据
    onMounted(() => {
      fetchDataSystem();
      fetchDataCompany();
      // fetchDataAnsers();
    });

    return {
      questionnaire,
      answers,
      submitAnswers,
      parames,
      selectCompanyOption,
      selectSystemOptions,
      selectedSystemMap,
      questionSystemSelections,
      dataSystem,
      dataCompany,
      handleSelectSystemChange,
      handleSelectComChange,
      companyName, 
      companyId,  
      cname,  
      textareaValue,
      clearValue,
    };
  },
};
</script>

<style>
.question-card {
  margin-bottom: 20px;
}

.el-checkbox-group{
  display: flex;
  flex-direction: column;
}

.el-radio-group {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.el-header {
  margin-bottom: 40px;
}

.el-header,
.el-footer {
  text-align: center;
}

.question_description {
  font-weight: bold;
}

.selectsty {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;

  .elselect {
    width: 100%;
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 10px;
  }
  .elselect>span{
    display: inline-block;
    width: 7%;
    min-width: 65px;
  }
  .elselect .el-select{
    display: inline-block;
    width: 88%;
  }
}
.highlighted {
  background-color: #cce8ff; /* 高亮的背景色，可以根据需求调整 */
  color: #0066cc;
  font-weight: bold;
}
.fixed-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  z-index: 1000;
  box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.el-main {
  padding-bottom: 60px !important; /* 根据 footer 的高度调整 */
}
</style>
